var matName,areaName,secInspe,dataInfo;
$(document).ready(function() {

    // $(".dynDiv input").css("border", "0px");
    // $(".dynDiv textarea").css("border", "0px");
    $.each($(".dynDiv").find('.table-bordered'), function () {
       $.each($(this).find('tr'), function () {
           $(this).find('th').last().css("border-right", "none");
           $(this).find('td').last().css("border-right", "none");
       })
    });
    $(".table-bordered").parent().parent().children().css("padding-left", "0px").css("padding-top", "0px").css("padding-bottom", "0px");
    $(".dynDiv").find("input").parent().css("text-indent", "0px");
    // $(".dynDiv").find("input[type='text']").css("height", "100%");
});

function validate_data() {
    var obj = null;
    var submitForm = $("#submitForm");
    if (val_purpose()) {
        obj = $($("input[name='finalUser']")[0]);
    } else {
        obj = null;
    }
    $.each($("#submitForm input"), function () {
        var dataRule = $(this).attr("data_rule");
        var disabled = $(this).attr("disabled");
        if (disabled == 'disabled') {
            return true;
        }
        if (panIsNull(dataRule)) {
            return true;
        }
        var details = dataRule.split(":");
        if (details[1] == 'required') {
            if ($(this).val() == null || $(this).val() == '') {
                layer.alert(details[0] + "的内容不可为空");
                // $(this).focus();
                obj = this;
                return false;
            }
        } else if (details[1] == 'email') {
            var reg = new RegExp(/^[\w\+\-]+(\.[\w\+\-]+)*@[a-z\d\-]+(\.[a-z\d\-]+)*\.([a-z]{2,4})$/i);
            if ($(this).val().match(reg) == null) {
                layer.alert(details[0] + "的邮箱格式错误");
                // $(this).focus();
                obj = this;
                return false;
            }
        } else if (details[1] == 'digits') {
            var reg = new RegExp(/^\d+$/);
            if ($(this).val().match(reg) == null) {
                layer.alert(details[0] + ",请输入数字");
                // $(this).focus();
                obj = this;
                return false;
            }
        } else if (details[1] == 'ID_card') {
            var reg = new RegExp(/^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[A-Z])$/);
            if ($(this).val().match(reg) == null) {
                layer.alert(details[0] + ",请输入正确的身份证号");
                // $(this).focus();
                obj = this;
                return false;
            }
        } else if (details[1] == 'date') {
            var reg = new RegExp(/^\d{4}-\d{1,2}-\d{1,2}$/);
            if ($(this).val().match(reg) == null) {
                layer.alert(details[0] + ",请输入正确的日期");
                // $(this).focus();
                obj = this;
                return false;
            }
        }
    });
    $.each($("#submitForm select"), function () {
        var dataRule = $(this).attr("data_rule");
        var disabled = $(this).attr("disabled");
        if (disabled == 'disabled') {
            return true;
        }
        if (panIsNull(dataRule)) {
            return true;
        }
        var details = dataRule.split(":");
        if (details[1] == 'required') {
            if ($(this).attr('leipiplugins') == 'select' && $(this).val() == '--请选择--') {
                layer.alert("请选择一项" + details[0]);
                // $(this).focus();
                obj = this;
                return false;
            }
        }
    });

    return obj;
}

function val_purpose() {
    if ($($("input[name='finalUser']")[0]).attr('disabled') == 'disabled') {
        return false;
    }
    var purpose = $($("select[name='purpose'] option:selected")[0]).val();
    var finalUser = $($("input[name='finalUser']")[0]).val();
    if (purpose == '自用') {
        if (panIsNull(finalUser)) {
            return false;
        } else {
            layer.alert("自用不可填写最终用户!");
            return true;
        }
    } else {
        if (panIsNull(finalUser)) {
            layer.alert("经销必须填写最终用户!");
            return true;
        } else {
            return false;
        }
    }
}

function parse_data(obj) {
    var keyWords = $(obj).val();
    var dataName = obj.getAttribute("orgdataname");
    if (panIsNull(dataName)) {
        return false;
    }
    var urlAndData = dataName.split("|");
    $.ajax({
        type:"POST"
        ,data:{"keyWords":keyWords}
        ,url:getRealPath()+urlAndData[0]
        ,dataType:"json"
        ,success:function (res) {
            var datas = urlAndData[1].split(",");
            if(res.status == 'SUCCESS'){
                for (var i in datas) {
                    var d = datas[i].split("=");
                    var dat = d[1].split('.');
                    if (dat.length == 1) {
                        $('input[name=' + d[0] + ']').val(res.data[dat[0]]);
                    } else if (dat.length == 2) {
                        $('input[name=' + d[0] + ']').val(res.data[dat[0]][dat[1]]);
                    } else if (dat.length == 3) {
                        $('input[name=' + d[0] + ']').val(res.data[dat[0]][dat[1]][dat[2]]);
                    }
                }
            } else {
                for (var dat in datas) {
                    var d = datas[dat].split("=");
                    $('input[name='+d[0]+']').val("");
                }
                layer.msg("未搜索到‘"+keyWords+"’,请确认名称或手动录入相关信息");
            }
        }
    });
}

function select_data(obj) {
    var dataName = obj.getAttribute("orgdataname");
    if (panIsNull(dataName)) {
        return false;
    }
    var urlAndData = dataName.split("|");
    dataInfo = urlAndData[1];
    layer.open({
        type: 2,
        title: false,
        maxmin: false,
        shadeClose: true, //点击遮罩关闭层
        area: ['820px', '500px'],
        content: [getRealPath()+urlAndData[0],'no']
    });
}

function setDataInfo(res) {
    var datas = dataInfo.split(",");
        for (var i in datas) {
            var d = datas[i].split("=");
            var dat = d[1].split('.');
            if (dat.length == 1) {
                $('input[name=' + d[0] + ']').val(res[dat[0]]);
            } else if (dat.length == 2) {
                $('input[name=' + d[0] + ']').val(res[dat[0]][dat[1]]);
            } else if (dat.length == 3) {
                $('input[name=' + d[0] + ']').val(res[dat[0]][dat[1]][dat[2]]);
            }
        }
}

function select_material(obj) {
    matName = $(obj).attr("name");
    layer.open({
        type: 2,
        title: '选择化学品',
        maxmin: false,
        shadeClose: true, //点击遮罩关闭层
        area : ['310px' , '450px'],
        content: getRealPath()+'/sysman/materialInfo/materialInfoList.do?openNewPro=New&openType=matparentfunc'
    });
}

function select_organs(obj) {
    areaName = $(obj).attr("name");
    layer.open({
        type: 2,
        title: '选择机关',
        maxmin: false,
        shadeClose: true, //点击遮罩关闭层
        area : ['310px' , '510px'],
        content: getRealPath()+'/sysman/systemArea/getAreaParentList.do?selecttype=callback'
    });
}

function select_check(obj) {
    secInspe = $(obj).attr("name");
    layer.open({
        type: 2,
        title: '检查项目',
        maxmin: false,
        shadeClose: true, //点击遮罩关闭层
        area : ['315px' , '455px'],
        content: getRealPath()+'/sysman/secInspe/SecInspeProPopup.do?areaId=0'
    });
}

function setMatVal(seedCnId, seedCnName, seedTypeId) {
    var matNames = document.getElementsByName(matName);
    matNames[0].value = seedCnName;
    // $("input[name='"+matName+"']").change();
}

function setCheck(inspeId, inspeName, inspeTypeId) {
    var secInspes = document.getElementsByName(secInspe);
    secInspes[0].value = inspeName;
    // $("input[name='"+matName+"']").change();
}

function setOrgContent(runOrgansId, runOrgansName, runOrgansType) {
    $("#runOrgansId").val(runOrgansId);
    $("#runOrgansType").val(runOrgansType);
    $($("input[name="+areaName+"]")[0]).val(runOrgansName);
    // $("table").find("input[title="+areaName+"]").change();
}

function parse_table(selector) {
    var tables = $(selector).find('table');
    for (var i = 0; i < tables.length; i++) {
        var table = tables[i];
        var json = [];
        if (!panIsNull($(table).attr("id")) && $(table).attr("id").endWith("_table")) {
            var trs = $(table).find('tbody').find('tr');
            for (var j = 0; j < trs.length; j++) {
                var tds = $(trs[j]).find('td');
                var tdLen = tds.length;
                if (panIsNull($(table).attr("orgreadonly"))) {
                    tdLen--;
                }
                for (var k = 0;k < tdLen; k++) {
                    var jsonStr = {};
                    jsonStr.fieldName = $(table).attr('name') + '[' + k + ']';
                    jsonStr.groupId = j;
                    // console.log($(tds[k]).children().first()[0]);
                    jsonStr.aliasName = $(tds[k]).children().first()[0].getAttribute("orgalias");
                    jsonStr.name = $(tds[k]).children().first()[0].getAttribute("name");
                    jsonStr.values = $(tds[k]).children().first().val();
                    json.push(jsonStr);
                }
            }
            $(selector).find("input[name=" + $(table).attr('name') + "]").remove();
        $(selector).append("<input type='hidden' name='" + $(table).attr('name') + "' value='" + JSON.stringify(json) + "'/>");
        }
    }
}

String.prototype.startWith=function(str){
    var reg=new RegExp("^"+str);
    return reg.test(this);
};

String.prototype.endWith=function(str){
    var reg=new RegExp(str+"$");
    return reg.test(this);
};

function get_data(obj, selector, isAdd) {
    $.ajax({
        type:"POST"
        ,data:{"serviceId":obj}
        ,url:getRealPath() + "/sysman/dynFormFieldValue/getValueByServiceId.do"
        ,dataType:"json"
        ,async:false
        ,success:function (res) {
            if(res.status == 'SUCCESS'){
                parseData(res.data, selector, isAdd);
            } else {
                layer.alert(res.msg);
            }
        }
    });
}

function parseData(resData, selector, isAdd) {
    for (var i = 0; i < resData.length; i++) {
        if (resData[i].fieldTextType == 'listctrl') {
            var values = resData[i].values;
            // for (var j in values) {
            //     $('[name='+values[j].name+']').val(values[j].value);
            // }
            var jsonVal = eval(values);
            if (isAdd) {
                for (var j = 0; j < jsonVal[jsonVal.length - 1].groupId; j++) {
                    tbAddRow(resData[i].name);
                }
            }
            loadData(values, selector);
            resData.splice(i, 1);
        }
        // $("[name="+res.data[i].aliasName+"]").val(res.data[i].values);
    }
    // console.log(resData);
    loadData(resData, selector);
}

// 加载数据
function loadData(dynFormData, selector){
    dynFormData = eval(dynFormData);
    for (var i = 0; i < dynFormData.length; i++) {
        var formData = dynFormData[i];
        var formDom = $(selector).find("input[name='"+formData.name+"']");
        if(formDom.length==0){
            formDom = $(selector).find("textarea[name='"+formData.name+"']");
        }
        if(formDom.length==0){
            formDom = $(selector).find("select[name='"+formData.name+"']");
        }
        if(formDom.length==0){
            continue;
        }
        var formType = $(formDom).attr("leipiplugins");
        if(panIsNull(formType)){
            formType = $(formDom).attr("type");
            if(panIsNull(formType)){
                formType = $(formDom).parent().attr("leipiplugins");
                if(panIsNull(formType)){
                    return;
                }
            }
        }

        if(formType == 'text' || formType == 'textarea'){
            if (!panIsNull($(formDom).val())) {
                continue;
            }
            $(formDom).val(formData.values);
        }
        if(formType == 'radios' || formType == 'radio'){
            $(selector).find("input[name='"+formData.name+"']:radio[value='"+formData.values+"']").attr('checked','true');
        }
        if(formType == 'checkboxs' || formType == 'checkbox'){
            $(selector).find("input[name='"+formData.name+"']:checkbox[value='"+formData.values+"']").attr('checked','true');
        }
        if(formType == 'select') {
            $(selector).find("select[name='"+formData.name+"']").children().removeAttr('selected');
            $(selector).find("select[name='"+formData.name+"']").children("[value='"+formData.values+"']").attr('selected', 'selected');
        }
    }
}

function clearDisabled(selector) {
    $(selector + " :input").removeAttr("disabled");
    // $("#submitForm :textarea").removeAttr("disabled");
    // $("#submitForm :select").removeAttr("disabled");
}
function setDisabled(selector) {
    $(selector + " :input").attr("disabled","disabled");
}

// function setDetailsMat() {
//     $.each($("#mat_table").find("tr"), function () {
//         var matInfo = $(this).find("td").first().children().first().val();
//         var num = 1;
//         $.each($(this).find("td"), function () {
//             var val = $(this).children().first().val();
//             if (matInfo == val) {
//                 return true;
//             } else {
//                 matInfo += " " + val;
//                 num++;
//                 $(this).remove();
//             }
//         });
//         $(this).find("td").first().attr("colspan", num).children().first().val(matInfo);
//     });
// }